#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <cstring>
#include <arpa/inet.h>
#include <memory>
#include "thread.hpp"
uint16_t severport = 0;
std::string serverip;

static void usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " serverIp serverPort\n"
              << std::endl;
}

static void *udpSend(void *args)
{
    int sock = *(int *)(((ThreadData *)args)->_args);
    std::string name = ((ThreadData *)args)->_name;

    std::string message;
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);

    server.sin_family = AF_INET;
    server.sin_port = htons(severport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());


    char buffer[1024];
    while (true)
    {
        std::cout << "请输入你的信息# ";
        std::getline(std::cin, message);
        if (message == "quit")
            break;

        // 当client首次发送消息给服务器的时候，OS会自动给client bind它的IP和port
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof server);
    }

    return nullptr;
}

static void* udpRecv(void *args)
{
    int sock = *(int *)(((ThreadData *)args)->_args);
    std::string name = ((ThreadData *)args)->_name;
    
    char buffer[1024];
    while (true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof temp;
        ssize_t s = recvfrom(sock, buffer, sizeof buffer, 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << " server echo# " << buffer << std::endl;
        }
    }
    return nullptr;
}


//  ./udp_client 127.0.0.1 8080
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }

    int sock = socket(AF_INET, SOCK_DGRAM, 0);

    if (sock < 0)
    {
        std::cout << "socket error" << std::endl;
        exit(2);
    }
    severport = atoi(argv[2]); // string  to  int
    serverip = argv[1];

    // client 要不要bind？要，但是一般client不会显式的去bind，程序员不会自己bind
    //  client是一个客户端->普通人下载安装启动使用的->如果程序员自己bind了->
    // client 一定bind了一个固定的ip和port，万一，其他客户端提前占用了这个port呢？
    //  client 一般不需要显式的bind指定port，而让OS自动的随机选择

    // 一个线程管收消息，一个线程管发消息
    std::unique_ptr<Thread> sender(new Thread(1, udpSend, (void*)&sock));
    std::unique_ptr<Thread> recver(new Thread(2, udpRecv, (void*)&sock));
    
    sender->start();
    recver->start();

    sender->join();
    recver->join();
    close(sock);

    return 0;
}